<?php

defined('SYSPATH') or die('No direct script access.');

class Task_Parse extends Minion_Task {

	/**
	 * Test action
	 *
	 * @param array $params
	 * @return void
	 */
	protected function _execute(array $params) {
		Minion_CLI::write(Minion_CLI::color(date('H:i:s') . ' - CIAN started', 'green'));
		$config = Kohana::$config->load('ads');
		$group = 'cian';
		if (!$config->offsetExists($group)) {
			throw new Ads_Exception('Failed to load Ads group: :group', array(':group' => $group));
		}
		$config = $config->get($group);
		$database = Arr::get($config, 'database', '');

		$cian = Ads::instance();
				$cianrds = Ads::instance('cianrds');

		Minion_CLI::write_replace(Minion_CLI::color(date('H:i:s') . ' - getting & parsing first page CIAN started', 'red'));
		$data = $cian->query('http://www.cian.ru/cat.php?deal_type=1&obl_id=1&city[0]=1&totime=600')->parse();
		Minion_CLI::write_replace(Minion_CLI::color(date('H:i:s') . ' - getting & parsing first page CIAN finished', 'green'), TRUE);
		Minion_CLI::write(Minion_CLI::color(date('H:i:s') . ' - found '.count($data).' Ads', 'yellow'));
		Minion_CLI::write_replace(Minion_CLI::color(date('H:i:s') . ' - writing CIAN data in database started', 'red'));
		$cian->write($data);
		$data = $cianrds->query('http://www.cian.ru/cat.php?deal_type=1&obl_id=1&city[0]=1&totime=600')->parse();
		$cianrds->write($data);
		Minion_CLI::write_replace(Minion_CLI::color(date('H:i:s') . ' - writing CIAN data in database finished', 'green'), TRUE);
		$count = DB::select(array(DB::expr('COUNT(DISTINCT `adsid`)'), 'adsids'))->from('ads')->execute($database)->get('adsids', 0);
		Minion_CLI::write(Minion_CLI::color(date('H:i:s') . ' - Ads in database: '.$count, 'yellow'));
		Minion_CLI::write(Minion_CLI::color(date('H:i:s') . ' - CIAN finished', 'green'));
	}

}

// End Sendmail
